package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {


    /**
     * spring-data 会自动注入IStrategyCommentRepository实现类
     *
     * IStrategyCommentRepository 接口继承MongoRepository
     * 拥有了 分页,排序,crud基本功能
     *    底层实现 : AOP 操作--动态代理
     */
    @Autowired
    private IStrategyCommentRepository repository;

    //使用较为底层的贾琏欲执事, 实现mongodb操作, 这里用它来实现较为复杂操作
    @Autowired
    private MongoTemplate template;


    @Override
    public void saveOrUpdate(StrategyComment comment) {
        if(comment.getId() == null){
            comment.setCreateTime(new Date());
        }
        repository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        Query query = new Query();
        if(qo.getDetailId() != -1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }

        long count = template.count(query, StrategyComment.class);

        // 优化
        if(count == 0){
            return Page.empty();
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(pageable);
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        return new PageImpl(list, pageable, count);
    }

    @Override
    public void thumbUp(String toid, Long userId) {
        // 点赞、取消点赞 是同个请求，如何区分
        // 解决方案：把点赞人 id 存到 list 中，请求进来时，判断 该 用户 id 是否在 list 中存在
        StrategyComment strategyComment = repository.findById(toid).get();
        if(strategyComment == null){
            return;
        }
        List<Long> list = strategyComment.getThumbuplist();
        // 存在就是取消点赞，把用户从 list 中删除，点赞数减一
        if(list.contains(userId)){
            list.remove(userId);
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() - 1);
        }else {
            // 不存在就是 点赞，把用户存到 list 中，点赞数加一
            list.add(userId);
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() + 1);
        }

        // 统一更新
//        strategyComment.setThumbuplist(list);
        repository.save(strategyComment);

    }
}
